<?php
/*******************************************************************************
 * 判断是否需要执行过滤/动作
 *******************************************************************************/
function has_filter(){
	global $__f_plugins;
	if(empty($__f_plugins)){
		return false;
	}
	$debug_backtrace = debug_backtrace(); // 堆栈信息
	//echo '<pre>';print_r($debug_backtrace);echo '</pre>';exit;
	$filter_name = strtolower($debug_backtrace[2]['class']) . '.' . $debug_backtrace[1]['function'];
	if(array_key_exists($filter_name, $__f_plugins)){
		return $__f_plugins[$filter_name];
	}
	return false;
}

function has_action($tpl_file){
	global $__f_theme;
	if(empty($__f_theme)){
		return false;
	}
	$key = md5($tpl_file);
	$_f_plugin_actions = cache_read('plugin_actions.php');
	if(!is_array($_f_plugin_actions))$_f_plugin_actions = array();
	if($__f_theme['seek'] == 1 || 
		(defined('PLUGIN_DEBUGGING') && PLUGIN_DEBUGGING == true)){
		$html = @file_get_contents($tpl_file);
		preg_match_all('/<!--\[\[\[\s*(\w+\.\w+)\s*-->/', $html, $matchs);
		if(!empty($matchs[1])){
			$_f_plugin_actions[$key] = $matchs[1];
			cache_write('plugin_actions.php', $_f_plugin_actions);
			return $matchs[1];
		}else{
			$_f_plugin_actions[$key] = false;			
		}
	}else{
		if(isset($_f_plugin_actions[$key])){
			return $_f_plugin_actions[$key];
		}
	}
	return false;
}
/*******************************************************************************
 * 执行过滤/动作
 *******************************************************************************/
function do_filter($data, $filter_info){
	foreach($filter_info as $func => $plugin_data){
		try{
			@include_once PLG_PTH.$plugin_data['plugin_file'];
			if(function_exists($func)){
				$data = call_user_func_array($func, array('data' => $data));
			}
		}catch(Exception $e){}
	}
	return $data;
}

function apply_action($actions){
	global $__f_plugins;
	/*if(!$__f_plugins = cache_read('plugins.php')){
		return false;
	}*/
	foreach($actions as $mark){
		if(!array_key_exists($mark, $__f_plugins)){
			continue;
		}
		$action_info = $__f_plugins[$mark];
		do_action($action_info);
	}
	return $GLOBALS['ars'];
}

function do_action($action_info){
	foreach($action_info as $func => $plugin_data){
		try{
			@include_once PLG_PTH.$plugin_data['plugin_file'];
			if(function_exists($func)){
				$data = call_user_func($func);
				if(is_array($data)){
					$GLOBALS['ars'] = array_merge($GLOBALS['ars'], $data);
				}else{
					$GLOBALS['ars'][$func] = $data;
				}
			}
		}catch(Exception $e){}
	}
	return true;
}

/*******************************************************************************
 * 获取插件
 *******************************************************************************/
function get_plugins($mark = ''){
	cache_delete('plugins.php');
	
	$plugin_files = $preview_files = array();
	$plugins_dir = @opendir(PLG_PTH);
	if($plugins_dir){
		while(($dir = readdir($plugins_dir)) !== false){
			if(substr($dir, 0, 1) == '.') continue;
			if(is_dir(PLG_PTH.$dir)){
				$plugins_subdir = @opendir(PLG_PTH.$dir);
				if($plugins_subdir){
					while(($file = readdir($plugins_subdir)) !== false){
						if(substr($file, 0, 1) == '.') continue;
						$ext = substr($file, -4);
						if($ext == '.php'){
							$mark = get_plugin_name("{$dir}/{$file}");
							$plugin_files[$mark] = "{$dir}/{$file}";
						}elseif(in_array($ext, array('.jpg', '.gif', '.png'))){
							$mark = get_plugin_name("{$dir}/{$file}");
							$preview_files[$mark] = "{$dir}/{$file}";
						}
					}
					closedir($plugins_subdir);
				}
			}
		
		// 插件根目录下暂时不允许有插件
		}
		closedir($plugins_dir);
	}

	$plugin_all = array();
	foreach($plugin_files as $mark => $plugin_file){
		$plugin_data = get_plugin_data($plugin_file, false, false); //Do not apply markup/translate as it'll be cached.
		if(empty($plugin_data['name'])) continue;
		if(array_key_exists($mark, $preview_files)){
			$plugin_data['preview'] = $preview_files[$mark];
		}else{
			$preview_file = preg_replace('/\.\w+/', '.preview', $mark);
			if(array_key_exists($preview_file, $preview_files)){
				$plugin_data['preview'] = $preview_files[$preview_file];
			}
		}
		if(array_key_exists($mark, $plugin_all)){
			$plugin_data = array_merge($plugin_all[$mark], $plugin_data);
		}
		$plugin_data['mark'] = $mark;
		$plugin_all[$mark] = $plugin_data;
	}
	//cache_write('plugin_all.php', $plugin_all);
	return $plugin_all;
}

function get_plugin_data($plugin_file){
	$file_data = file_get_contents(PLG_PTH . $plugin_file);
	preg_match('/\/\*\*\s+#CC#\s+[\S\s]+?\*\//', $file_data, $match);
	if(empty($match)) return false;
	$cofnig = str_replace('\\~', '#wave#', $match[0]);
	$headers = array('mark', 'name', 'url', 'version', 'desc', 'author', 'date');
	$plugin_data = array('plugin_file' => $plugin_file); // 记录文件路径
	foreach($headers as $key){
		preg_match("/\s*~\s*{$key}\s*[：:]\s*([^~]+)/", $cofnig, $submatch);
		if(!empty($submatch)){
			$submatch[1] = trim($submatch[1]);
			$submatch[1] = preg_replace('/\*\/$/', '', $submatch[1]);
			$submatch[1] = preg_replace('/\s+$/', '', $submatch[1]);
			$plugin_data[$key] = str_replace('#wave#', '~', $submatch[1]);
		}
	}
	return $plugin_data;
}

function get_plugin_name($plugin_file){
	return str_replace(array('/', '.php', '.jpg', '.gif', '.png'), array('.', '', '', '', ''), $plugin_file);
}
/*******************************************************************************
 * 激活插件
 *******************************************************************************/
function activate_plugin($mark, $active = 1){
	if(!$plugin_all = cache_read('plugin_all.php')){
		return false;
	}
	$plugin_data = $plugin_all[$mark];
	$plugin_data['state'] = $active;
	$plugin_data['updatetime'] = TIME;
	##if(!isset($GLOBALS['plugin_funcs']))$GLOBALS['plugin_funcs'] = array();
	try{
		$GLOBALS['plugin'] = array('do' => 'activate', 'activate' => $active, 'plugin_data' => $plugin_data, '__relation' => array());
		include_once PLG_PTH.$plugin_data['plugin_file'];
		##cache_write('plugins.php', $GLOBALS['plugin_funcs']);	// 可以考虑把这个搬到外面的函数，这样就只执行一次
	}catch(Exception $e){
		return false;
	}
	return $GLOBALS['plugin']['__relation'];
}

function add_filter($tag, $func){
	if(!isset($GLOBALS['plugin']) || $GLOBALS['plugin']['do'] != 'activate'){
		return false;
	}
	// 函数检测
	if(!function_exists($func)){
		return false;
	}
	/*if(!$_plugins = cache_read('plugins.php')){
		$_plugins = array('__relation' => array());
	}*/
	$_plugins = $GLOBALS['plugin_funcs'];
	if(!isset($_plugins[$tag]))$_plugins[$tag] = array();
	$mark = $GLOBALS['plugin']['plugin_data']['mark'];
	if($GLOBALS['plugin']['activate'] == 1){
		$_plugins[$tag][$func] = array(
			'mark'			=> $mark,
			'plugin_file'	=> $GLOBALS['plugin']['plugin_data']['plugin_file'],
		);
		if(!isset($_plugins['__relation'][$mark]))$_plugins['__relation'][$mark] = array('filters' => array(), 'actions' => array());
		if(!isset($_plugins['__relation'][$mark]['filters'][$tag]))$_plugins['__relation'][$mark]['filters'][$tag] = array();
		$_plugins['__relation'][$mark]['filters'][$tag][$func] = 1;
	}else{
		if(isset($_plugins[$tag][$func]))unset($_plugins[$tag][$func]);
		if(empty($_plugins[$tag]))unset($_plugins[$tag]);
		
		if(isset($_plugins['__relation'][$mark]['filters'][$tag][$func])){
			$_plugins['__relation'][$mark]['filters'][$tag][$func] = 0;
		}
	}
	$GLOBALS['plugin']['__relation']['filters'] = $_plugins['__relation'][$mark]['filters'];
	//return cache_write('plugins.php', $_plugins);
	$GLOBALS['plugin_funcs'] = $_plugins;
}

function add_action($tag, $func){
	if(!isset($GLOBALS['plugin']) || $GLOBALS['plugin']['do'] != 'activate'){
		return false;
	}
	// 函数检测
	if(!function_exists($func)){
		return false;
	}
	/*if(!$_plugins = cache_read('plugins.php')){
		$_plugins = array('__relation' => array());
	}*/
	$_plugins = $GLOBALS['plugin_funcs'];
	if(!isset($_plugins[$tag]))$_plugins[$tag] = array();
	$mark = $GLOBALS['plugin']['plugin_data']['mark'];
	if($GLOBALS['plugin']['activate'] == 1){
		$_plugins[$tag][$func] = array(
			'mark'			=> $mark,
			'plugin_file'	=> $GLOBALS['plugin']['plugin_data']['plugin_file'],
		);
		if(!isset($_plugins['__relation'][$mark]))$_plugins['__relation'][$mark] = array('filter' => array(), 'actions' => array());
		if(!isset($_plugins['__relation'][$mark]['actions'][$tag]))$_plugins['__relation'][$mark]['actions'][$tag] = array();
		$_plugins['__relation'][$mark]['actions'][$tag][$func] = 1;
	}else{
		if(isset($_plugins[$tag][$func]))unset($_plugins[$tag][$func]);
		if(empty($_plugins[$tag]))unset($_plugins[$tag]);
		
		if(isset($_plugins['__relation'][$mark]) && 
				isset($_plugins['__relation'][$mark]['actions']) &&
				isset($_plugins['__relation'][$mark]['actions'][$tag]) &&
				isset($_plugins['__relation'][$mark]['actions'][$tag][$func])){
			$_plugins['__relation'][$mark]['actions'][$tag][$func] = 0;
		}
	}
	$GLOBALS['plugin']['__relation']['actions'] = $_plugins['__relation'][$mark]['actions'];
	//return cache_write('plugins.php', $_plugins);
	$GLOBALS['plugin_funcs'] = $_plugins;
}
/*******************************************************************************
 * 删除插件
 *******************************************************************************/
//function del_filter($tag, $func){
//	if(!$_plugins = cache_read('plugins.php')){
//		return true;
//	}
//	if(!isset($_plugins[$tag])){
//		return true;
//	}
//	if(!isset($_plugins[$tag][$func])){
//		return true;
//	}
//	unset($_plugins[$tag][$func]);
//	if(empty($_plugins[$tag])){
//		unset($_plugins[$tag]);
//	}
//	return cache_write('plugins.php', $_plugins);
//}
//
//function del_action($tag, $func){
//
//}

//function del_plugin($marks){
//	if(!$plugin_all = cache_read('plugin_all.php')){
//		return false;
//	}
//	$plugin_all = array_slice($plugin_all, 1);
//	foreach($plugin_all as $mark => $plugin_data){
//		if(in_array($mark, $marks)){
//			unset($plugin_all[$mark]);
//		}
//	}
//	$plugin_all['time'] = TIME;
//	return cache_write('plugin_all.php', $plugin_all);
//}
?>